<template>
  <LoginFormTitle v-show="getShow" class="enter-x" />
  <Form
    class="p-4 enter-x"
    :model="formData"
    :rules="getFormRules"
    ref="formRef"
    v-show="getShow"
    @keypress.enter="handleLogin"
  >
    <FormItem name="account" class="enter-x">
      <Input
        size="large"
        v-model:value="formData.account"
        :placeholder="t('sys.login.userName')"
        class="fix-auto-fill"
      />
    </FormItem>
    <FormItem name="password" class="enter-x">
      <InputPassword
        size="large"
        visibilityToggle
        v-model:value="formData.password"
        :placeholder="t('sys.login.password')"
      />
    </FormItem>

    <ARow class="enter-x">
      <ACol :span="12">
        <FormItem>
          <!-- No logic, you need to deal with it yourself -->
          <Checkbox v-model:checked="rememberMe" size="small">
            {{ t('sys.login.rememberMe') }}
          </Checkbox>
        </FormItem>
      </ACol>
      <ACol :span="12">
        <FormItem :style="{ 'text-align': 'right' }">
          <!-- No logic, you need to deal with it yourself -->
          <Button type="link" size="small" @click="setLoginState(LoginStateEnum.RESET_PASSWORD)">
            {{ t('sys.login.forgetPassword') }}
          </Button>
        </FormItem>
      </ACol>
    </ARow>

    <FormItem class="enter-x">
      <Button type="primary" size="large" block @click="handleLogin" :loading="loading">
        {{ t('sys.login.loginButton') }}
      </Button>
      <!-- <Button size="large" class="mt-4 enter-x" block @click="handleRegister">
        {{ t('sys.login.registerButton') }}
      </Button> -->
    </FormItem>
    <ARow class="enter-x" :gutter="[16, 16]">
      <ACol :md="8" :xs="24">
        <Button block @click="setLoginState(LoginStateEnum.MOBILE)">
          {{ t('sys.login.mobileSignInFormTitle') }}
        </Button>
      </ACol>
      <ACol :md="8" :xs="24">
        <Button block @click="setLoginState(LoginStateEnum.QR_CODE)">
          {{ t('sys.login.qrSignInFormTitle') }}
        </Button>
      </ACol>
      <ACol :md="8" :xs="24">
        <Button block @click="setLoginState(LoginStateEnum.REGISTER)">
          {{ t('sys.login.registerButton') }}
        </Button>
      </ACol>
    </ARow>

    <Divider class="enter-x">{{ t('sys.login.otherSignIn') }}</Divider>

    <div class="flex justify-evenly enter-x" :class="`${prefixCls}-sign-in-way`">
      <GithubFilled />
      <WechatFilled />
      <AlipayCircleFilled />
      <GoogleCircleFilled />
      <TwitterCircleFilled />
    </div>
  </Form>
</template>
<script lang="ts" setup>
  import { reactive, ref, unref, computed } from 'vue';

  import { Checkbox, Form, Input, Row, Col, Button, Divider } from 'ant-design-vue';
  import {
    GithubFilled,
    WechatFilled,
    AlipayCircleFilled,
    GoogleCircleFilled,
    TwitterCircleFilled,
  } from '@ant-design/icons-vue';
  import LoginFormTitle from './LoginFormTitle.vue';

  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';

  import { useUserStore } from '/@/store/modules/user';
  import { LoginStateEnum, useLoginState, useFormRules, useFormValid } from './useLogin';
  import { useDesign } from '/@/hooks/web/useDesign';
  //import { onKeyStroke } from '@vueuse/core';

  import coreTool from '/@/tool/coreTool'
  import coreAxios from '/@/tool/coreAxios'
  import { useCoreToolStore } from '/@/store/modules/cn/core/tool/coreToolStore'
  import type { Res } from '/@/tool/Res'
  import type { Param } from '/@/tool/Param'
  import type { LoginAO } from '/@/model/cn/core/tool/ao/LoginAO'
  import type { LoginVO } from '/@/model/cn/core/tool/vo/LoginVO'

  import type { UserInfo } from '/#/store'
  import { RoleEnum } from '/@/enums/roleEnum'
  import { PageEnum } from '/@/enums/pageEnum'
  import { router } from '/@/router'
  import { message } from 'ant-design-vue'

  const ACol = Col;
  const ARow = Row;
  const FormItem = Form.Item;
  const InputPassword = Input.Password;
  const { t } = useI18n();
  const { notification, createErrorModal } = useMessage();
  const { prefixCls } = useDesign('login');
  const userStore = useUserStore();

  const { setLoginState, getLoginState } = useLoginState();
  const { getFormRules } = useFormRules();

  const formRef = ref();
  const loading = ref(false);
  const rememberMe = ref(false);

  const formData = reactive({
    // account: 'vben',
    // password: '123456',
    account: '',
    password: '',
  });

  const { validForm } = useFormValid(formRef);

  //onKeyStroke('Enter', handleLogin);

  const getShow = computed(() => unref(getLoginState) === LoginStateEnum.LOGIN);

  const coreToolStore = useCoreToolStore();

  async function handleLogin() {
    const data = await validForm();
    if (!data) return;
    try {
      loading.value = true;

      let { account, password } = data
      let param: Param<LoginAO> = {
        data: [
          {
            loginSide: 'Browser',
            account: account,
            password: coreTool.encodeAES(password, coreTool.aesKey),
          },
        ],
      }
      coreToolStore.login(param).then(async (res: Res<LoginVO>) => {
        if (res.succ) {
          let { msg, accountId, usrId, usrname, avatarUrl, token, aesKey, authList, switchPostLoginInfo, allDictValueMapInfo, allConfMapInfo } = res.data[0]
          coreTool.ls.set('coreToken', token)
          coreTool.ls.set('coreAesKey', coreTool.aesKeyDecode ? coreTool.decodeRSAByPrivateKey(aesKey, coreTool.privateKey) : aesKey)
          coreAxios.defaults.headers['Authorization'] = coreTool.ls.get!('coreToken') || 'token'
          coreTool.ls.set('switchPostLoginInfo', switchPostLoginInfo)
          coreTool.ls.set('allDictValueMapInfo', allDictValueMapInfo)
          coreTool.ls.set('fileUrlPrefix', allConfMapInfo.fileUrlPrefix)
          await coreToolStore.setSwitchPostLoginInfo(switchPostLoginInfo)
          await coreToolStore.setAllDictValueMapInfo(allDictValueMapInfo)
          await coreToolStore.setFileUrlPrefix(allConfMapInfo.fileUrlPrefix)
          await userStore.setToken(token)
          let userInfo: UserInfo = {
            userId: usrId,
            username: account,
            realName: usrname,
            avatar: coreToolStore.getFileFullUrl(avatarUrl),
            desc: usrname,
          }
          await userStore.setUserInfo(userInfo)
          await userStore.setRoleList(authList as RoleEnum[])
          let sessionTimeout = userStore.sessionTimeout
          sessionTimeout && await userStore.setSessionTimeout(false)
          let goHome = true
          !sessionTimeout && goHome && (await router.replace(PageEnum.BASE_HOME))
          message.success(msg)
          // dictStore.getAllDictValueMapInfo().then((res: Res<object>) => {
          //   if (res.succ) {
          //     coreTool.ls.set('allDictValueMapInfo', res.data[0])
          //     coreToolStore.setAllDictValueMapInfo(res.data[0])
          //   } else {
          //     message.error(res.msg, 6)
          //   }
          // })
        } else {
          message.error(res.msg, 6)
        }
      })

      // const userInfo = await userStore.login({
      //   password: data.password,
      //   username: data.account,
      //   mode: 'none', //不要默认的错误提示
      // });
      // if (userInfo) {
      //   notification.success({
      //     message: t('sys.login.loginSuccessTitle'),
      //     description: `${t('sys.login.loginSuccessDesc')}: ${userInfo.realName}`,
      //     duration: 3,
      //   });
      // }
    } catch (error) {
      createErrorModal({
        title: t('sys.api.errorTip'),
        content: (error as unknown as Error).message || t('sys.api.networkExceptionMsg'),
        getContainer: () => document.body.querySelector(`.${prefixCls}`) || document.body,
      });
    } finally {
      // loading.value = false;
      setTimeout(() => { loading.value = false }, 6000);
    }
  }
</script>
